package cn.texous.web.parsing.book.publisher.fiction;

import cn.texous.util.commons.util.upgrade.Optional;
import cn.texous.web.parsing.book.concurrent.AnaThreadPoolExecutor;
import cn.texous.web.parsing.book.model.bo.publisher.AnaChapterAddOrUpdateBO;
import cn.texous.web.parsing.book.model.entity.mysql.AnaBookChapter;
import cn.texous.web.parsing.book.publisher.AnaSubscribe;
import cn.texous.web.parsing.book.service.api.mysql.AnaBookChapterService;
import cn.texous.web.parsing.book.service.api.mysql.AnaUserBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author Showa.L
 * @since 2019/7/25 19:21
 */
@Component
public class AnaChapterSubscribe implements AnaSubscribe<AnaChapterAddOrUpdateBO> {

    /**
     * 订阅的 topic
     */
    public static final String TOPIC = "CHAPTER_ADD";

    @Autowired
    private AnaBookChapterService anaBookChapterService;
    @Autowired
    private AnaThreadPoolExecutor anaThreadPoolExecutor;

    @Override
    public void onEvent(AnaChapterAddOrUpdateBO object) {
        Optional.ofNullable(object).ifPresent(c -> insertOrUpdate(object));
    }

    @Override
    public String getTopic() {
        return TOPIC;
    }

    private void insertOrUpdate(AnaChapterAddOrUpdateBO updateBO) {
        anaThreadPoolExecutor.execute(() -> {
            AnaBookChapter chapter = new AnaBookChapter();
            chapter.setCode(updateBO.getAnaBookChapterCode());
            chapter.setWords(updateBO.getContent().length());
            chapter.setContent(updateBO.getContent());
            anaBookChapterService.updateByCode(chapter);
        });
    }
}
